<?php

namespace app\home\controller;

// 引入前台公共控制器
use app\common\controller\Home;

class Index extends Home
{
    public function __construct()
    {
        parent::__construct();

        $this->SubjectModel = model('Subject.Subject');
        $this->ChapterModel = model('Subject.Chapter');
        $this->CommentModel = model('Subject.Comment');
        $this->OrderModel = model('Subject.Order');
    }

    public $NoLogin = ['*'];

    // 会员模型
    protected $SubjectModel;
    protected $ChapterModel;
    protected $CommentModel;
    protected $OrderModel;

    public function index()
    {
        $top = $this->SubjectModel->order('createtime desc')->limit(5)->select();

        $list = $this->SubjectModel->order('id desc')->limit(8)->select();

        $data = [
            'top' => $top,
            'list' => $list,
        ];

        $this->assign($data);

        // 渲染一个模板页面
        return $this->view->fetch();
    }
    public function register()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            if (empty($mobile) || empty($password)) {
                $this->error('手机号或密码不能为空');
            }

            // 生成一个密码盐
            $salt = randstr();

            // 对密码进行加密
            $password = md5($password . $salt);

            // 组装数据
            $data = [
                'mobile' => $mobile,
                'nickname' => $mobile,
                'password' => $password,
                'salt' => $salt,
                'gender' => '0', //性别
                'deal' => '0', //成交状态
                'money' => '0', //余额
                'auth' => '0', //实名认证
            ];

            // 查询客户来源id
            $sourceid = model('common/Business/Source')->where(['name' => ['LIKE', "%云课堂%"]])->value('id');

            if ($sourceid) {
                $data['sourceid'] = $sourceid;
            }

            $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            if ($result === false) {
                // 失败
                $this->error($this->BusinessModel->getError());
                exit;
            } else {
                // 注册成功条状登录页
                $this->success('注册成功', url('home/index/login'));
                exit;
            }
        }

        return $this->view->fetch();
    }
    public function login()
    {
        // 判断是否为微信浏览器访问
        if (isWechat()) {
            $openid = session('openid') ? session('openid') : '';

            if (empty($openid)) {
                $this->redirect(url('home/wechat/oauth'));
                exit;
            } else {
                $business = $this->BusinessModel->where(['openid' => $openid])->find();

                if ($business) {
                    $this->view->assign('isWechatLogin', true);
                }
            }
        }

        if ($this->request->isPost()) {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            $ckeck = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if (!$ckeck) {
                $this->error('手机号或密码错误');
                exit;
            }

            $salt = $ckeck['salt'];
            $password = md5($password . $salt);

            if ($ckeck['password'] != $password) {
                $this->error('手机号或密码错误');
                exit;
            }

            // 当是微信浏览器且资料中的openid为空的时候 就更新 
            if (isWechat() && empty($ckeck['openid'])) {
                //判断是否有openid
                $openid = session('openid') ? session('openid') : '';

                if (!empty($openid)) {
                    $update = [
                        'id' => $ckeck['id'],
                        'openid' => $openid
                    ];

                    $result = $this->BusinessModel->isUpdate(true)->save($update);

                    if ($result === false) {
                        $this->error('授权绑定用户失败');
                        exit;
                    }
                }
            }

            $cookie = [
                'id' => $ckeck['id'],
                'mobile' => $ckeck['mobile']
            ];

            cookie('business', $cookie);

            $this->success('登录成功', url('home/business/index'));

            exit;
        }

        return $this->view->fetch();
    }
    public function logout()
    {
        // 清除cookie
        cookie('business', null);
        $this->success('退出成功', url('home/index/login'));
        exit;
    }
    public function info()
    {
        $pid = $this->request->param('pid', 0, 'trim');

        // 判断课程是否存在
        $subject = $this->SubjectModel->find($pid);

        if (!$subject) {
            $this->error('课程不存在', url('home/index/index'));
            exit;
        }

        // 是否点赞
        $subject['isLike'] = false;


        // 查询课程章节
        $chapter = $this->ChapterModel->where(['subid' => $pid])->select();

        // 查询课程评论
        $comment = $this->CommentModel->with(['business'])->where(['subid' => $pid])->limit(8)->select();
        // 课程评论数量
        $commentCount = $this->CommentModel->where(['subid' => $pid])->count();

        // echo $this->CommentModel->getLastSql();
        // exit;

        // 判断是否登录
        $business = $this->queryBusiness();

        if ($business) {
            $busid = $business['id'];
            $links = $subject['likes'];

            if (!empty($links)) {
                $links = explode(',', $links);

                if (in_array($busid, $links)) {
                    $subject['isLike'] = true;
                }
            }
        }

        // 注入数据
        $this->assign([
            'subject' => $subject,
            'chapter' => $chapter,
            'comment' => $comment,
            'hasMoreComments' => $commentCount > count($comment),
        ]);

        return $this->view->fetch();
    }
    public function like()
    {
        if ($this->request->isAjax()) {
            $subid = $this->request->param('subid', 0, 'trim');

            $business = $this->queryBusiness();

            if (!$business) {
                $this->error('请先登录');
                exit;
            }

            $subject = $this->SubjectModel->where(['id' => $subid])->find();

            if (!$subject) {
                $this->error('课程不存在');
                exit;
            }

            $links = $subject['likes'];

            $links = empty($links) ? [] : explode(',', $links);

            $isLike = in_array($business['id'], $links);

            if ($isLike) {
                $index = array_search($business['id'], $links);

                // 删除用户id
                unset($links[$index]);
            } else {
                // 添加用户id
                $links[] = $business['id'];
            }

            // 对数组去重
            $links = array_unique($links);
            $links = implode(',', $links);

            // 更新数据
            $result = $this->SubjectModel->isUpdate(true)->save([
                'likes' => $links,
                'id' => $subid
            ]);

            $msg = $isLike ? '取消点赞' : '点赞';

            if ($result) {
                $this->success($msg . '成功');
            } else {
                $this->error($msg . '失败');
            }
            exit;
        }
    }
    public function search()
    {
        if ($this->request->isAjax()) {
            // 接收参数
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $search = $this->request->param('search', '', 'trim');

            $where = [];

            if (!empty($search)) {
                $where['title'] = ['LIKE', "%$search%"];
            }

            // 查询总数
            $count = $this->SubjectModel->where($where)->count();

            $start = ($page - 1) * $limit;

            $data = $this->SubjectModel
                ->with(['category'])
                ->where($where)
                ->order('createtime desc')
                ->limit($start, $limit)
                ->select();

            if (empty($data)) {
                $this->error('暂无更多数据');
                exit;
            } else {
                $this->success('ok', null, [
                    'data' => $data,
                    'count' => $count
                ]);
                exit;
            }
        }
        return $this->view->fetch();
    }
    public function play()
    {
        if ($this->request->isAjax()) {
            // 课程id
            $subid = $this->request->param('subid', '', 'trim');
            // 章节id
            $cid = $this->request->param('cid', '', 'trim');

            // 判断课程是否存在
            $subject = $this->SubjectModel->find($subid);

            if (!$subject) {
                $this->error('课程不存在');
                exit;
            }

            // 判断章节是否存在
            $chapter = $this->ChapterModel->find($cid);

            if (!$chapter) {
                $chapter = $this->ChapterModel->where('subid', $subid)->order('id', 'asc')->find();

                if (empty($chapter)) {
                    $this->error('该课程无章节');
                    exit;
                }
            }

            $business =  $this->queryBusiness();

            if (!$business) {
                $this->error('请先登录');
                exit;
            }

            $where = [
                'subid' => $subid,
                'busid' => $business['id'],
            ];

            // 在订单列表查询该用户是否购买该课程
            $order = $this->OrderModel->where($where)->find();

            if ($order) {
                $this->success('您已购买该课程', null, $chapter);
            } else {
                $this->success('您未购买该课程', null, ['status' => 'buy']);
            }
            exit;
        }
    }
    public function buy()
    {
        if ($this->request->isAjax()) {
            // 课程id
            $subid = $this->request->param('subid', '', 'trim');

            // 判断课程是否存在
            $subject = $this->SubjectModel->find($subid);

            if (!$subject) {
                $this->error('课程不存在');
                exit;
            }

            $business =  $this->queryBusiness();

            if (!$business) {
                $this->error('请先登录');
                exit;
            }

            $where = [
                'subid' => $subid,
                'busid' => $business['id'],
            ];

            // 在订单列表查询该用户是否购买该课程
            $order = $this->OrderModel->where($where)->find();

            // 防止重复购买
            if ($order) {
                $this->error('您已购买该课程');
                exit;
            }

            // 加载消费记录模型
            $RecordModel = model('Business.Record');

            // 开启事务
            $RecordModel->startTrans();
            $this->BusinessModel->startTrans();
            $this->OrderModel->startTrans();

            // 用户余额
            $money = empty($business['money']) ? 0 : $business['money'];
            // 课程价格
            $price = empty($subject['price']) ? 0 : $subject['price'];
            // 价格不能小于0
            if ($price < 0) {
                $this->error('课程价格错误');
                exit;
            }

            // 两个高精度的浮点数相减
            $newMoney = bcsub($money, $price);

            // 判断余额是否充足
            if ($newMoney < 0) {
                $this->error('您的余额不足');
                exit;
            }

            // 生成订单号
            $code = build_code("SUB");

            // 订单数据
            $orderData = [
                'subid' => $subid,
                'busid' => $business['id'],
                'code' => $code,
                'total' => $price,
            ];

            $orderResult = $this->OrderModel->validate('comon/Subject/Order')->save($orderData);

            // 插入失败
            if (!$orderResult) {
                $this->OrderModel->rollback();
                $this->error($this->OrderModel->getError());
                exit;
            }

            // 更新用户余额
            $businessData = [
                'id' => $business['id'],
                'money' => $newMoney,
            ];

            // 用户余额验证器
            $businessMoneyValidate = [
                [
                    'money' => 'require|number|>=:0'
                ],
                [
                    'money.require' => '余额未知',
                    'money.number' => '余额必须是数字',
                    'money.>=' => '余额必须是大于等于0元',
                ]
            ];

            // 更新数据
            $businessResult = $this->BusinessModel->validate(...$businessMoneyValidate)->isUpdate(true)->save($businessData);

            if (!$businessResult) {
                $this->OrderModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }
            $title = $subject['title'];
            $content = "购买课程：【{$title}】花费了 ￥$price 元";

            // 插入消费记录
            $recordData = [
                'total' => $price,
                'busid' => $business['id'],
                'content' => $content,
            ];

            $recordResult = $RecordModel->validate('common/Business/Record')->save($recordData);

            if (!$recordResult) {
                $this->BusinessModel->rollback();
                $this->OrderModel->rollback();
                $this->error($RecordModel->getError());
                exit;
            }

            if (!$orderResult || !$businessResult || !$recordResult) {
                $RecordModel->rollback();
                $this->BusinessModel->rollback();
                $this->OrderModel->rollback();
                $this->error('课程购买失败');
                exit;
            } else {
                $this->BusinessModel->commit();
                $this->OrderModel->commit();
                $RecordModel->commit();

                if (!empty($business['openid'])) {
                    $cdnurl = config('site.cdnurl') ? config('site.cdnurl') : '';
                    $cdnurl = trim($cdnurl, '/');

                    //组装数据
                    $data = [
                        'touser' => $business['openid'],
                        'template_id' => 'gUN3X-cwRUt18jBjyS9KIwIJ_Xm7HuVIDQANEbdBksw',
                        'url' => url('home/index/info', ['pid' => $subid], true, true),
                        'data' => [
                            'time' => date("Y-m-d H:i", time()),
                            'money' => $price,
                            'name' => $title
                        ]
                    ];

                    $WechatController = new \app\home\controller\Wechat();

                    $WechatController->template($data);
                }


                $this->success('课程购买成功');
                exit;
            }
        }
    }
    public function commentList()
    {
        if ($this->request->isAjax()) {
            $commentModel = model('Subject.Comment');

            $business = $this->BusinessData;
            // collection()->toArray()
            // 接收参数
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');

            $start = ($page - 1) * $limit;

            // 查询总数
            $count = $commentModel->with(['business'])->where(['busid' => $business['id']])->count();

            $orderList = $commentModel
                ->with(['business'])
                ->where(['busid' => $business['id']])
                ->order('createtime desc')
                ->limit($start, $limit)
                ->select();

            if (empty($orderList)) {
                $this->error('暂无更多数据');
                exit;
            } else {
                $this->success('ok', null, [
                    'data' => $orderList,
                    'count' => $count
                ]);
                exit;
            }
        }

        return $this->view->fetch();
    }
}
